<?php
/**
 * class App_Model_Abstract
 *
 * @author kim
 */
class App_Model_Abstract
{
    /**
     * table primary id
     */
    protected $_primary = 'id';

    /**
     * table name
     */
    protected $_name = '';

    /**
     * adapter of table object
     *
     * Zend_Db_Table
     */
    protected $_table = null;

    /**
     * cache object
     * Zend_Cache_Core
     */
    protected $_cache = null;

    /**
     * get table object
     */
    public function getTable()
    {
        return $this->_table;
    }

    /**
     * set table object
     */
    public function setTable($table)
    {
        $this->_table = $table;
    }

    /**
     * set cache object
     */
    public function setCache($cache)
    {
        $this->_cache = $cache;
    }

    /**
     * get cache object
     */
    public function getCache()
    {
        return $this->_cache;
    }

    /**
     * construct function
     *
     * 1. set up table object
     * 2. set up cache object
     */
    public function __construct()
    {
        if ($this->_name) {
            $table = new Zend_Db_Table($this->_name);
            if ($this->_primary) {
                $table->setOptions(array(
                    Zend_Db_Table::PRIMARY => $this->_primary
                ));
            }
            $this->setTable($table);
        } else {
            throw new Exception(__CLASS__ . ' : You must assign the table name of current table!');
        }

        if (Zend_Registry::isRegistered('table_cache')) {
            $this->setCache(Zend_Registry::get('table_cache'));
        }
    }

    /**
     * try to fetch data from cache
     *
     * @param string $id the cache id
     * @return false|array
     */
    protected function _fetchCache($id)
    {
        $result = false;
        $cache = $this->getCache();
        if ($cache instanceof Zend_Cache_Core) {
            $result = $cache->load($id);
        }
        return $result;
    }

    /**
     * try to save data into cache
     *
     * @param array $data the data to be cached
     * @param string $id the cache id
     * @return true
     */
    protected function _saveCache($data, $id)
    {
        $cache = $this->getCache();
        if ($cache instanceof Zend_Cache_Core) {
            $cache->save($data, $id);
        }
        return true;
    }

}
